package BlogMybatis.blog.service.impl;

import BlogMybatis.blog.pojo.Message;
import BlogMybatis.blog.mapper.MessageMapper;
import BlogMybatis.blog.service.MessageService;
import BlogMybatis.blog.service.QQMailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Brandt
 * @since 2020-06-17
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private QQMailService qqMailService;
    @Autowired
    private TemplateEngine templateEngine;

    //创建10个线程
    private Executor executor = Executors.newFixedThreadPool(10);

    //存放迭代找出的所有子代的集合
    private List<Message> tempReplys = new ArrayList<>();

    @Override
    public List<Message> listMessage() {
        //根据前端默认给父级评论id(-1)，查询出父节点
        List<Message> messages = messageMapper.findByParentIdNull(Long.parseLong("-1"));
        for (Message message : messages) {
            //拿到父节点数据库中的id
            Long id = message.getId();
            //父节点的昵称
            String parentNickname1 = message.getNickname();
            //根据父节点id查询子回复
            List<Message> childMessages = messageMapper.findByParentIdNotNull(id);
            //查询子评论
            combineChildren(childMessages,parentNickname1);
            message.setReplyMessages(tempReplys);
            tempReplys = new ArrayList<>();
        }
        return messages;
    }

    @Override
    public int saveMessage(Message message) {
        if(message.getParentMessage().getId() != null){
            message.setParentMessageId(message.getParentMessage().getId());
        }
        message.setCreateTime(new Date());
        return messageMapper.insert(message);
    }


    //查询子回复
    private void combineChildren(List<Message> childMessages,String parentNickname1){
        //先判断是否有一级子回复，如果有，循环找出子回复的id
        if(childMessages.size() > 0){
            for (Message childMessage : childMessages) {
                //拿到一级子回复的昵称，作为二级子回复要回复的谁
                String parentNickname = childMessage.getNickname();
                //设置一级子回复要评论的父级昵称
                childMessage.setParentNickname(parentNickname1);
                tempReplys.add(childMessage);
                //拿到一级子回复的id，根据这id作为二级回复的父id，查询二级以下的所有子回复
                Long childId = childMessage.getId();
                //查询二级以下所有的子集回复
                recursively(childId,parentNickname);
            }
        }
    }

    //迭代找出子集回复。根据一级回复的id和一级回复的昵称parentNickname1作为二级回复的父节点，
    //找出所有二级以下的回复
    private void recursively(Long childId,String parentNickname1){
        List<Message> replayMessages = messageMapper.findByReplayId(childId);
        if(replayMessages.size() > 0){
            for (Message replayMessage : replayMessages) {
                //查询出二级回复的昵称
                String parentNickname = replayMessage.getNickname();
                replayMessage.setParentNickname(parentNickname1);
                //查询出二级回复的id
                Long replayId = replayMessage.getId();
                tempReplys.add(replayMessage);
                //循环迭代找出所有子集回复
                recursively(replayId,parentNickname);
            }
        }
    }

    @Override
    public void findParentMessage(Message message) {
        Message parentMessage = message.getParentMessage();
        if(parentMessage == null){
            return;
        }else {  //如果parentMessage不为空，根据获取它的id，获取父级评论
            Message parent = messageMapper.selectById(parentMessage.getId());
            //查看父级评论是否开了邮件回复通知
            Boolean flag = parent.getReplyInform();
            if(flag){  //如果开了就给父级评论发送邮件信息
                Runnable task = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //创建邮件正文
                            Context context = new Context();
                            //设置邮件模板可变参数
                            context.setVariable("parentMessage",parent);
                            context.setVariable("message",message);
                            //解决表情显示问题
                            String content1 = parent.getContent();
                            String content2 = message.getContent();
                            String replace1 = content1.replace("/images", "http://www.xiaozhu888.top/images");
                            String replace2 = content2.replace("/images", "http://www.xiaozhu888.top/images");
                            context.setVariable("replace1", replace1);
                            context.setVariable("replace2", replace2);
                            context.setVariable("sendTime", new Date());
                            String emailTemplate = templateEngine.process("emailTemplate", context);
                            qqMailService.sendHtmlMail(parent.getEmail(),"你收到一条来自(Brandt_博客)的回复",emailTemplate);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                };
                executor.execute(task);
            }else {
                return;
            }
        }
    }
}
